<!--
 * @Author: wang_jl
 * @Date: 2021-07-14 10:32:55
 * @LastEditTime: 2021-12-13 19:29:23
 * @LastEditors: wei_jt@ecidi.com
 * @Description: 扫码登录
-->
<template>
  <div>
    <div class="code_name">
      {{ codeVal.name }}
    </div>
    <div id="ercodeShow" />
  </div>
</template>
<script>
import { loadScript } from '@/utils/util'
export default {
  name: 'ErCode',
  props: ['codeVal'],
  data() {
    return {}
  },
  watch: {
    codeVal(val) {
      if (this.codeVal.key == 'DINGTALK') {
        this.dingdingLogin(this.codeVal)
      }
    }
  },
  created() {
    if (this.codeVal.key == 'DINGTALK') {
      loadScript(
        'https://g.alicdn.com/dingding/dinglogin/0.0.5/ddLogin.js',
        () => {
          this.dingdingLogin(this.codeVal)
        }
      )
    }
  },
  methods: {
    //钉钉登录
    dingdingLogin(val) {
      this.sourceType = val
      this.dingtalkLogin = !this.dingtalkLogin
      this.dingtalkLoginSrc = `${this.VUE_APP_THIRD_PARTY_API}${val.key}`
      var xhr = new XMLHttpRequest()
      xhr.open('GET', this.dingtalkLoginSrc, true)
      xhr.onload = function () {
        this.dingtalkLoginSrc = xhr.responseText
        var obj = DDLogin({
          id: 'ercodeShow',
          goto: encodeURIComponent(this.dingtalkLoginSrc),
          style: 'border:none;color:#fffff;background-color:transparent;',
          width: '300',
          height: '300'
        })
        let reg = /https:\/\/oapi.dingtalk.com\/connect\/qrconnect\?response_type=code&appid=(.*?)&scope=snsapi_login&redirect_uri=(.*?)&state=(.*?)$/
        let list = this.dingtalkLoginSrc.match(reg)
        let apiCode = list[1]
        let redUrl = list[2]
        let state = list[3]
        let hanndleMessage = function (event) {
          let origin = event.origin
          //判断是否来自ddLogin扫码事件
          if (origin === 'https://login.dingtalk.com') {
            let loginTmpCode = event.data
            //这里url不用进行urlencode编码
            if (loginTmpCode) {
              let url = `https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=${apiCode}&response_type=code&scope=snsapi_login&state=${state}&redirect_uri=${redUrl}&loginTmpCode=${loginTmpCode}`
              window.location.href = url
            }
          }
        }
        if (typeof window.addEventListener !== 'undefined') {
          window.addEventListener('message', hanndleMessage, false)
        } else if (typeof window.attachEvent !== 'undefined') {
          window.attachEvent('onmessage', hanndleMessage)
        }
      }
      xhr.send(null)
    }
  }
}
</script>
<style lang="scss">
.code_name {
  margin-bottom: 40px;
  font-size: 20px;
  text-align: center;
  color: #555;
}

#ercodeShow {
  width: 300px;
  height: 300px;
  margin: 0 auto;
  box-shadow: 0 3px 10px 0 rgba(0, 0, 0, 0.1);
}
</style>